//
//  SettingsTabViewController.m
//  Seizure
//
//  Created by student on 2/9/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SettingsTabViewController.h"
#import "AlertPrompt.h"
#import "DataManager.h"
#import "LinkedAccount.h"
#import "LogViewController.h"

@implementation SettingsTabViewController


@synthesize associatedCaretakers;
@synthesize editCaretakerButton;
@synthesize table;
@synthesize logOutButton;
@synthesize showLogsButton;

@synthesize customView;
NSArray *array;

typedef enum {
    GET_CARETAKERS,
    ADD_CARETAKER
} requestTypes;
static NSString * const FAKE_ACCOUNT_LOGOUT = @"Attempting To Log Out";

// required methods
#pragma mark -
#pragma mark Table Data Source methods

// number of rows in a section
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [associatedCaretakers count] +1;
}
// returns cell to render

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"CellIdentifier";
    LinkedAccount *acc;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    else {
        // grabbed a reused cell, set accessory view and color to defaults 
        cell.accessoryView = nil;
        cell.textLabel.textColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f];
    }
    if (indexPath.row >= [associatedCaretakers count])
    {
        cell.textLabel.text = @"Add new Caretaker";
        cell.detailTextLabel.text = nil;
        UIButton *addbutton = [UIButton buttonWithType:UIButtonTypeContactAdd];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        [addbutton addTarget:self action:@selector(addCaretaker:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = addbutton;
    }
    else{
        
        acc = (LinkedAccount *)[associatedCaretakers objectAtIndex:indexPath.row];
        if (acc.status == STATUS_CONFIRMED){
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryNone;
            [[cell textLabel] setText:acc.name];
            cell.detailTextLabel.text = acc.email;
        }
        else if (acc.status == STATUS_WAITING){
            [[cell textLabel] setText:acc.email];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.detailTextLabel.text = @"Waiting for response...";
            cell.textLabel.textColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f];
        }
        else if (acc.status == STATUS_PENDING) {
            cell.textLabel.text = acc.name;
            cell.detailTextLabel.text = @"Tap to respond.";
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//            cell.accessoryView = customView;
        }
                 
    }
    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row >= [associatedCaretakers count]){
        return UITableViewCellEditingStyleNone;
    }
    else
    {
        return UITableViewCellEditingStyleDelete;
    }
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"Caretakers";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // add caretaker cell was clicked
    if (indexPath.row >= associatedCaretakers.count){
        [self addCaretaker:nil];
    }
    else
    {
        LinkedAccount *selected = [associatedCaretakers objectAtIndex:indexPath.row];
        if (selected.status == STATUS_PENDING){
            NSString *message = [NSString stringWithFormat:@"Request from %@ with email %@. \n Do you want this person to recieve alerts and view your log information?", selected.name, selected.email];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Request" message:message delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
            [alert show];
        }
    }
}

// when delete is selected
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    // If row is deleted, remove it from the list.
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        //Save the email of the Caretaker we're removing to remove it from the database.
        LinkedAccount *accountRemoved = [associatedCaretakers objectAtIndex:indexPath.row];
        NSString *emailRemoving = accountRemoved.email;
        
        //Update the database
        DataManager *dm = [DataManager sharedInstance];
        Account *currentAccount = [dm.local retrieveAccount];
        BOOL success = [dm removePatientCaretakerConnection:currentAccount emailToDisconnect:emailRemoving];

        // delete your data item here if database removal succeeded
        if( success )
        {
            [associatedCaretakers removeObjectAtIndex:indexPath.row];
        
            // Animate the deletion from the table.
            [self.table deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            if ([associatedCaretakers count] == 0)
                [table setEditing:NO animated:YES];
        }
        else
        {
            NSString *message = [NSString stringWithFormat:@"We're sorry! We were unable to remove this Caretaker: %@", emailRemoving];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Removal Failed" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
        }
    }
}

#pragma mark -
#pragma mark NetworkData
// this gets called when an http request is successful
- (void)DataArrived:(id)dataObject requestType:(int)rtype
{
    if (rtype == GET_CARETAKERS){
        [associatedCaretakers addObjectsFromArray:(NSArray *)dataObject];

        // refresh the table  from the main queue/thread instead of the NSOperation from DBCommunicator
        // http://stackoverflow.com/a/8146782/121654 , otherwise table doesn't reload instantly
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            [table reloadData];
        });   
    }
}

////////////////////////////
#pragma mark -
#pragma mark AlertPrompt delegation

// handles the button press action after adding caretaker
// TODO: Handle adding a new caretaker
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // the user clicked one of the OK/Cancel buttons
    if ( buttonIndex == 1 && [actionSheet isMemberOfClass:[AlertPrompt class]] )
    {
        // create caretaker data
        NSString *email = [(AlertPrompt *)actionSheet enteredText];
        LinkedAccount *newCaretaker = [[LinkedAccount alloc ] init];
        newCaretaker.email = email;
        newCaretaker.status = STATUS_WAITING;
        
        // dispatch data-manager to do a http operation sending information
        DataManager *dm = [DataManager sharedInstance];
        Account *userAccount = [dm.local retrieveAccount];
        NSString *emailOfRequested = newCaretaker.email;
        NSString *result = [dm createPatientCaretakerConnection:userAccount emailOfRequested:emailOfRequested];
        
        // insert to table cell
        if([result isEqualToString:@""])
        {
            [associatedCaretakers insertObject:newCaretaker atIndex:(associatedCaretakers.count)];
            [table reloadData];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add Unsuccessful" message:result delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
        }
    }
    else if( actionSheet.title == FAKE_ACCOUNT_LOGOUT )
    {
        if( buttonIndex == 1 )
        {
            DataManager *dm = [DataManager sharedInstance];
            [dm userLoggedOut];
            [self.parentViewController.navigationController setNavigationBarHidden:NO animated:YES];
            [self.parentViewController.navigationController popToRootViewControllerAnimated:YES];
        }
        else
            return;
        
    }
    //It was not an AlertPrompt, just a regular UIAlertView coming from Confirming a Connection
    //User pressed OK button
    else if( buttonIndex == 1 )
    {
        int row = [table indexPathForSelectedRow].row;
        LinkedAccount *currSelected = [associatedCaretakers objectAtIndex:row];
        NSString *caretakerEmail = currSelected.email;
        
        DataManager *dm = [DataManager sharedInstance];
        [dm confirmPatientCaretakerConnection:caretakerEmail];

        currSelected.status = STATUS_CONFIRMED;
        [table reloadData];
    }
    else
    { // canceled
        [table deselectRowAtIndexPath:[table indexPathForSelectedRow] animated:YES];
        [table reloadRowsAtIndexPaths:[[NSArray alloc] initWithObjects:[table indexPathForSelectedRow], nil] withRowAnimation:NO];
    }
}

// present keyboard, only after AlertView is fully presented
-(void)didPresentAlertView:(UIAlertView *)alertView{
    if ([alertView isKindOfClass:([AlertPrompt class])])
        [[(AlertPrompt*)alertView textField] becomeFirstResponder];
}

#pragma mark -
#pragma mark other methods


/**
 * Adds a caretaker to the database, 
 */
- (IBAction)addCaretaker:(id)sender
{
    AlertPrompt *addCaretaker = [[AlertPrompt alloc] initWithTitle:@"Add Caretaker" message:@"\n\n\n" delegate:self
                                                 cancelButtonTitle:@"Cancel" okButtonTitle:@"Add" placeholderText:nil];
    [addCaretaker show];
}



// switch editing modes
- (IBAction)editMode:(id)sender
{
    static BOOL editing = NO;
    if (!editing && [associatedCaretakers count] > 0){
        
        [table setEditing:YES animated:YES];
        editing = YES;
    }
    else
    {
        [table setEditing:NO animated:YES];
        editing = NO;
    }
}


- (IBAction)userLoggedOut
{
    DataManager *dm = [DataManager sharedInstance];

    if( dm.usingFakeAccount )
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:FAKE_ACCOUNT_LOGOUT message:@"You are about to log out. If you do, you will lose all of your saved logs. Press \"OK\" to continue logging out or \"Cancel\" to stay logged in" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        [alert show];
    }
    else
    {
        [dm userLoggedOut];
    
        [self.parentViewController.navigationController setNavigationBarHidden:NO animated:YES];
        [self.parentViewController.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (IBAction)showLogs
{
    LogViewController *patientLogsView = [[LogViewController alloc] initWithNibName:@"LogViewController" bundle:nil];
    [self.navigationController pushViewController:patientLogsView animated:YES];
}


// setup nib
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    associatedCaretakers = [[NSMutableArray alloc] init ];

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"Settings" image:nil tag:1];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    DataManager *dm = [DataManager sharedInstance];
    [dm fetchCaretakers:self requestType:GET_CARETAKERS];
    
    // remove caretaker views if account is local only (fake)
    if ([dm usingFakeAccount])
    {
        [table setHidden:YES];
        [editCaretakerButton setHidden:YES];
        [hiddenDescription setHidden:NO];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
